package com.link.play.fit.ai.ui.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class AutoSwitchTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val handler = Handler(Looper.getMainLooper())
    private var texts: List<String> = emptyList()
    private var currentIndex = 0
    private var interval: Long = 2500 // 默认2.5秒
    private var isRunning = false

    private val runnable = object : Runnable {
        override fun run() {
            if (texts.isNotEmpty()) {
                currentIndex = (currentIndex + 1) % texts.size
                text = texts[currentIndex]

                // 设置随机间隔（2000-3000ms）
                val nextDelay = (2000..3000).random()
                handler.postDelayed(this, nextDelay.toLong())
            }
        }
    }

    // 设置文本列表
    fun setTextList(textList: List<String>) {
        this.texts = textList
        if (textList.isNotEmpty()) {
            text = textList.first()
        }
    }

    // 设置固定间隔（可选）
    fun setSwitchInterval(millis: Long) {
        interval = millis
    }

    // 开始切换
    fun startSwitching() {
        if (!isRunning && texts.size > 1) {
            isRunning = true
            handler.postDelayed(runnable, interval)
        }
    }

    // 停止切换
    fun stopSwitching() {
        handler.removeCallbacks(runnable)
        isRunning = false
    }

    // 自动清理防止内存泄漏
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopSwitching()
    }
}